package com.yxh.controller;

import com.github.pagehelper.PageInfo;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.yxh.common.annotation.Authorization;
import com.yxh.pojo.*;
import com.yxh.service.FlowManageService;
import com.yxh.service.MakingsService;
import com.yxh.service.ViciousService;
import com.yxh.util.*;
import net.sf.json.JSONObject;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by asus on 2018/7/4.
 */

@Scope("prototype")
@RestController
@RequestMapping(value = "/makings")
public class MakingsController extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(MakingsController.class);
    private Response response;


    @Autowired
    private MakingsService makingsService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private FlowManageService flowManageService;


    @Autowired
    private ViciousService viciousService;

    /***新增 启动档案流程
     *
     * @param makings
     * @return
     */
    @PostMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response saveChange(@RequestBody Makings makings) {
        String id= SnowflakeIdWorker.creatId();
        makings.setMakingsId(id);
        response = Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(makingsService.save(makings));

        //启动流程  保存记录
        Map<String,Object> variables = new HashMap<String, Object>();
        variables.put("makingsId",id);
        variables.put("code",makings.getMakingsCode());
        variables.put("user2",makings.getAuditingId());//材料准备人员

        flowManageService.start(variables, TaskCode.MAKE_KEY.getDesc(), TaskCode.OPERATION_MEG8.getDesc(),TaskCode.OPERATION_COMMENT11.getDesc());

        History h=new History();
        h.setOperationName(TaskCode.OPERATION_MEG8.getDesc());
       // h.setState(TaskCode.OPERATION_COMMENT11.getDesc());
        h.setViciousId(id);
        h.setComment(TaskCode.OPERATION_COMMENT11.getDesc());
        h.setUserid(makings.getLoggedUser());

        h.setPresideId(makings.getAuditingId());

        int  i=viciousService.insertHistroy(h);

        return response;


    }

    @GetMapping("/task/{id}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response list(@RequestParam(required = false, defaultValue = "1", name = "page") String page,
                         @RequestParam(required = false, defaultValue = "10", name = "pageSize") String pageSize,
                         @PathVariable(value = "id") String id) throws Exception {

        try {

            //查询当前流程的任务
            List<Task> taskList= flowManageService.taskList(page,pageSize,id,TaskCode.MAKE_KEY.getDesc());

            List<MyTask> tasks = new ArrayList<MyTask>();

            for (Task task : taskList) {
                String makingsId= (String) taskService.getVariable(task.getId(), "makingsId");
                MyTask t = new MyTask();
                t.setId(task.getId());
                t.setName(task.getName());
                t.setCreateTime(task.getCreateTime());
                Map<String,Object> m=makingsService.getById(makingsId);
                t.setModel(m==null?0:m);
                tasks.add(t);
            }
            //对数据进行转换
            JSONObject result=flowManageService.changeData(tasks,TaskCode.CHANGE_KEY.getDesc(),id);

            response= Response.returnResponse(APIErrorCode.SUCCESS);
            response.setData(result);
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.SELECT_ERROR);
        }

        return response;
    }

    @PostMapping("/audit")
    // @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response audit(@RequestBody TaskParam param){

        Map<String, Object> variables = new HashMap<String, Object>();
        String taskId=param.getTaskId(),nextId=param.getNextId(),cs="",imgs=param.getUrl(),
                makingsId= (String) taskService.getVariable(taskId, "makingsId"),megs="",operation="",m="";
        int state,i=0;
        try{
            state=param.getState();
        }catch(Exception e){
            state=0;
        }
        Makings ms=new Makings();
        if(state!=0){
            variables.put("meg",state);

            if(state==TaskCode.STATE_1.getValue()){
                // 整理合格
                variables.put("user1",nextId);
                operation=TaskCode.OPERATION_MEG10.getDesc();
                megs=TaskCode.OPERATION_COMMENT13.getDesc();
                cs=TaskCode.OPERATION_COMMENT13.getDesc();
                m=TaskCode.STATE_MEG21.getDesc();
            }

            if(state==TaskCode.STATE_2.getValue()){
                //整理不合格
                operation=TaskCode.OPERATION_MEG10.getDesc();
                megs=TaskCode.OPERATION_COMMENT14.getDesc();
                cs=TaskCode.OPERATION_COMMENT14.getDesc();
                m=TaskCode.STATE_MEG22.getDesc();
            }
            if(state==TaskCode.STATE_3.getValue()){
                //审核通过
                operation=TaskCode.OPERATION_MEG11.getDesc();
                megs=TaskCode.OPERATION_COMMENT13.getDesc();
                cs=TaskCode.OPERATION_COMMENT13.getDesc();
                m=TaskCode.STATE_MEG4.getDesc();
                ms.setStopDate(DateUtils.getDate());
            }
            if(state==TaskCode.STATE_4.getValue()){
                //审核不通过
                operation=TaskCode.OPERATION_MEG11.getDesc();
                megs=TaskCode.OPERATION_COMMENT14.getDesc();
                cs=TaskCode.OPERATION_COMMENT14.getDesc();
                m=TaskCode.STATE_MEG20.getDesc();
            }
        }

        else{
            operation=TaskCode.OPERATION_MEG9.getDesc();
            megs=TaskCode.OPERATION_COMMENT12.getDesc();
            variables.put("user",nextId);
            cs=TaskCode.STATE_MEG19.getDesc();
            m=TaskCode.STATE_MEG20.getDesc();

        }



        //保存历史记录

        History h=new History();
        h.setOperationName(operation);
        h.setState(cs);
        h.setViciousId(makingsId);
        h.setComment(param.getComment());
        h.setUserid(param.getUserId());
        if(param.getList().size()!=0){
            String id= SnowflakeIdWorker.creatId();
            flowManageService.insertImgs(param.getList(),id);
            h.setImgId(id);
        }
        h.setPresideId(nextId);

       i=viciousService.insertHistroy(h);

        //更改变更清单状态

        ms.setMakingsId(makingsId);
        ms.setState(m);
        makingsService.updata(ms);

        //提交流程
        flowManageService.complete(taskId,variables,operation,megs);

        response= Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(i);
        return response;
    }


    @GetMapping("/{id}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response list(@PathVariable(value = "id") String id) throws Exception {

        try {
            response= Response.returnResponse(APIErrorCode.SUCCESS);
            response.setData(makingsService.getById(id));
        } catch (Exception e) {
            e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.SELECT_ERROR);
        }

        return response;
    }

    @GetMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response getInformation(Makings change, String page, String pageSize) {
        Integer limit;
        Integer offset;
        try {
            limit = Integer.parseInt(page);
            offset = Integer.parseInt(pageSize);
        } catch (Exception e) {
            limit = 1;
            offset = 10;
        }
        //  vicious.setDay(DateUtils.parseDate(vicious.getDate()));
        PageInfo pageInfo = makingsService.getInformation(change, limit, offset);
        response = Response.returnResponse(APIErrorCode.SUCCESS);
        response.setData(pageInfo);
        return response;
    }
}
